package com.springboot.shiro.realm;

import com.springboot.shiro.mapper.MenuMapper;
import com.springboot.shiro.mapper.RoleMapper;
import com.springboot.shiro.mapper.UserMapper;
import com.springboot.shiro.pojo.Menu;
import com.springboot.shiro.pojo.Role;
import com.springboot.shiro.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @Date: 2019/10/23 15:06
 * @author: ybzhu
 * @Description：自定义 realm
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 身份验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名 密码
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String loginName = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());
        //从数据库查询用户信息
        User user = this.userMapper.findByUserName(loginName);
        if (user == null) {
            throw new UnknownAccountException("用户名或密码错误！");
        }
        if (!password.equals(user.getPassword())) {
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        if ("1".equals(user.getLocked())) {
            throw new LockedAccountException("账号已被锁定,请联系管理员！");
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
        return info;
    }

    /**
     * 权限授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //获取用户角色
        Set<Role> roles =this.roleMapper.findRolesByUserId(user.getId());
        //添加角色
        SimpleAuthorizationInfo authorizationInfo =  new SimpleAuthorizationInfo();
        for (Role role : roles) {
            authorizationInfo.addRole(role.getRoleName());
        }
        //获取用户权限
        Set<Menu> menus = this.menuMapper.findMenuByRoleId(roles);
        //添加权限
        for (Menu menu:menus) {
            authorizationInfo.addStringPermission(menu.getPermission());
        }
        return authorizationInfo;
    }

}
